package cmj.cloudmusic.activity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import cmj.cloudmusic.R;


public class MediaDemoActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText music;
    private MediaPlayer player;
    private ImageButton playBtn;
    private SeekBar seekBar;
    private Timer timer;
    private TimerTask task;
    private boolean isChange;//默认没有拖拽

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_demo);
        initViews();
    }

    private void initViews(){
        music=(EditText)findViewById(R.id.music);
        playBtn=(ImageButton)findViewById(R.id.play);
        seekBar=(SeekBar)findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            //开始触摸
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChange=true;
            }

            //停止触摸
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //设置歌曲的进度为当前seekBar的进度
                player.seekTo(seekBar.getProgress());
                isChange=false;
            }
        });
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
        findViewById(R.id.restart).setOnClickListener(this);
        findViewById(R.id.copy).setOnClickListener(this);
        //输入框修改监听
        music.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //当音乐发生变化时，停止播放
//                stopPlay();
            }
        });
        player=new MediaPlayer();
        Uri uri=Uri.parse(music.getText().toString());
        try {
            player.setDataSource(this, uri);
            //异步加载媒体流
            player.prepareAsync();
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //准备完毕
                    //开启定时器设置进度条
                    initTimer();
                    Toast.makeText(MediaDemoActivity.this, "歌曲准备完毕", Toast.LENGTH_SHORT).show();
                    player.start();
                    playBtn.setImageResource(R.drawable.a8t);
                    findViewById(R.id.back).setOnClickListener(MediaDemoActivity.this);
                    playBtn.setOnClickListener(MediaDemoActivity.this);
                    findViewById(R.id.to).setOnClickListener(MediaDemoActivity.this);
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    //错误监听
                    Toast.makeText(MediaDemoActivity.this, "无网络或歌曲链接无效", Toast.LENGTH_SHORT).show();
                    return false;
                }
            });
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //播放完毕
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initTimer(){
        //设置进度条长度
        seekBar.setMax(player.getDuration());
        timer=new Timer();
        task=new TimerTask() {
            @Override
            public void run() {
                //定时器执行：设置进度条
                if(!isChange) {
                    seekBar.setProgress(player.getCurrentPosition());
                }
            }
        };
        timer.schedule(task,0,1000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                startPlay();
                break;
            case R.id.pause:
                if(player!=null) {
                    player.pause();
                }
                break;
            case R.id.stop:
                stopPlay();
                break;
            case R.id.restart:
                restartPlay();
                break;
            case R.id.copy:
                music.setText("http://yinyueshiting.baidu.com/data2/music/35491386/35491386.mp3?xcode=203f769a62f8551131189f16455400eb");
                break;
            case R.id.back:
                backPlay();
                break;
            case R.id.play:
                play();
                break;
            case R.id.to:
                toPlay();
                break;
        }
    }

    private void play(){
        //判断当前是否正在播放歌曲
        if(player.isPlaying()) {
            //播放就暂停
            playBtn.setImageResource(R.drawable.a8t);
            player.pause();
        } else {
            //未播放就开始播放
            playBtn.setImageResource(R.drawable.a8v);
            player.start();
        }
    }

    private void toPlay() {
        //快进5秒
        //先获取当前正在播放的位置
        int currentPosition=player.getCurrentPosition();
        //获取歌曲总长度
        int duration=player.getDuration();
        //当前位置添加五秒后不大于歌曲总长度才可以添加
        if(duration>currentPosition+5000) {
            //当前位置添加五秒钟
            player.seekTo(currentPosition+5000);
        } else {
            Toast.makeText(MediaDemoActivity.this, "大于总长度了", Toast.LENGTH_SHORT).show();
        }
    }

    private void backPlay() {
        //回退5秒钟
        //先获取当前播放的位置
        int currentPosition=player.getCurrentPosition();
        //当前位置减少五秒钟小于0
        if(currentPosition-5000>0) {
            //当前位置减少五秒钟
            player.seekTo(currentPosition - 5000);
        } else {
            Toast.makeText(MediaDemoActivity.this, "小于0秒钟", Toast.LENGTH_SHORT).show();
        }
    }

    private void stopPlay() {
        if(player!=null) {
            //停止播放
            player.stop();
            //释放资源
            player.release();
            //对象置空
            player=null;
        }
    }

    private void restartPlay() {
        if(player!=null) {
            //重置媒体
            player.reset();
            player=null;
        }
        startPlay();
    }

    /**
     * 播放
     */
    private void startPlay() {
        if(player!=null) {
            player.start();
        } else {
            player=new MediaPlayer();
            Uri uri=Uri.parse(music.getText().toString());
            try {
                player.setDataSource(this, uri);
                //异步加载媒体流
                player.prepareAsync();
                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        //准备完毕
                        player.start();
                    }
                });
                player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        //错误监听
                        Toast.makeText(MediaDemoActivity.this, "无网络或歌曲链接无效", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //播放完毕
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        stopPlay();
        task.cancel();
        timer.cancel();
        task=null;
        timer=null;
        super.onDestroy();
    }
}
